package com.zthz.douxing

import com.google.common.eventbus.Subscribe
import com.zthz.douxing.event.UserWillDepartEvent
import com.zthz.douxing.sendmessageservice.thirdmessagesender.BaseMessageSenderService
import org.quartz.JobDataMap

import javax.annotation.PostConstruct

class UserWillTripMsgEventHandleService {

    boolean lazyInit = false
    
    def eventBusService
    def quartzScheduler
    def redisService
    def config
    def commonUtilService
    def orderXingeMessageService

    @PostConstruct
    def init(){
        eventBusService.register(this)
    }


    /**
     * 接受到任务后，将该任务添加到quartz中去。等待执行
     * @param event
     */
    @Subscribe
    def handleWillTripEvent(UserWillDepartEvent event) {
        //这些信息必须有。没有就返回错误

        if((event.xgToken!=null&&!event.xgToken.equals(""))||
           event.getuiId!=null&&!event.getuiId.equals("")){
            if(!event.username)
                return
        }
        CityInfo cityInfo = CityInfo.findByNameCn(event.tripSegment.arriveCity)
        if(cityInfo){
            event.cityCode = cityInfo.code
        }

        if(!event.validate()){
            //TODO 处理错误
            return
        }
        JobDataMap jobDataMap = new JobDataMap()
        jobDataMap.put("eventBusService", eventBusService)
        jobDataMap.put("redisService", redisService)
        jobDataMap.put("userWillTripEvent", event)
        jobDataMap.put("commonUtilService",commonUtilService)
        jobDataMap.put("orderXingeMessageService",orderXingeMessageService)
        jobDataMap.put("quartzScheduler",quartzScheduler)

        if(commonUtilService.getConfig("MessageSend4XingeJob")?.planform){
            BaseMessageSenderService baseMessageSenderService = commonUtilService.getBean(
                                commonUtilService.getConfig("MessageSend4XingeJob")?.planform)
            if(baseMessageSenderService)
                jobDataMap.put("baseMessageSenderService",baseMessageSenderService)
            else
                return
        }else
            return

        List handlers = commonUtilService.getConfigDataList('MessageSend4XingeJob')
        if(handlers?.size()>0){

            for(def it : handlers){
                try {
                    it.handle(jobDataMap)
                }catch (Exception e){
                    continue
                    log.debug(e.getMessage(),e.printStackTrace())
                }
            }
        }

    }

    @Override
    public String toString() {
        return com.google.common.base.Objects.toStringHelper(this)
                .add("eventBusService", eventBusService)
                .add("quartzScheduler", quartzScheduler)
                .toString();
    }
}